<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>添加新闻</h1>
    新闻标题 ：<input type="text" class="title" name="" id=""><br>
    新闻内容 ：<input type="text" class="content" name="" id=""><br>
    新闻图像 ：<input type="file" class="img" name="" id=""><br>

    <button class="btn">添加新闻</button>
    <script>
        // 点击添加新闻 
        /* 
            1.获取数据
            2.把数据通过ajax提交给后端
            3. 后端处理数据并返还
        */
        let titleEle = document.querySelector(".title");
        let contentEle = document.querySelector(".content");
        let imgEle = document.querySelector(".img");
        let btnEle = document.querySelector(".btn");
        btnEle.onclick = function(){
            let title = titleEle.value;
            let content = contentEle.value;
            let img = imgEle.files[0];
            let form = new FormData();
            form.append("title",title);
            form.append("content",content);
            form.append("img",img);
            let xhr = new XMLHttpRequest();
            xhr.open("post","/addnews");
            xhr.send(form);
            xhr.onreadystatechange = function(){
                if(xhr.readyState===4 && xhr.status===200){
                    // console.log(xhr.responseText);
                    let res = JSON.parse(xhr.responseText);
                    if(res.status===1){
                        alert("添加成功");
                        window.location.href = "/listShow";
                    }
                }
            }
        }



    </script>
</body>

</html>